package com.nsgf.library.photopicker.widget;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.matisse.Matisse;
import com.nsgf.library.matisse.MimeType;
import com.nsgf.library.matisse.engine.impl.GlideEngine;
import com.nsgf.library.matisse.internal.entity.CaptureStrategy;
import com.nsgf.library.matisse.listener.OnCheckedListener;
import com.nsgf.library.matisse.listener.OnSelectedListener;
import com.nsgf.library.photopicker.PhotoPicker;
import com.nsgf.library.photopicker.PhotoPreview;
import com.nsgf.library.photopicker.utils.PermissionsUtils;
import com.nsgf.library.utils.SysUtil;
import com.nsgf.library.utils.ToastUtils;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import io.reactivex.rxjava3.functions.Consumer;


/**
 * Created by donglua on 15/5/31.
 */
public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> {

    private ArrayList<WorkOrderDetailBean.FileDto> photoPaths;
    private LayoutInflater inflater;

    private Context mContext;

    private int size;

    private int index;
    private Set<MimeType> mimeTypes = MimeType.ofImage();

    public void setAction(@MultiPickResultView.MultiPicAction int action) {
        this.action = action;
    }

    private int action;
    private int drawable = R.drawable.__picker_ic_camera_n;


    public PhotoAdapter(Context mContext, ArrayList<WorkOrderDetailBean.FileDto> photoPaths) {
        this.photoPaths = photoPaths;
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
        padding = dip2Px(8);

    }

    public PhotoAdapter(Context mContext, ArrayList<WorkOrderDetailBean.FileDto> photoPaths, int size) {
        this.photoPaths = photoPaths;
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
        padding = dip2Px(8);
        this.size = size;

    }

    public PhotoAdapter(Context mContext, ArrayList<WorkOrderDetailBean.FileDto> photoPaths, int size, int index) {
        this.photoPaths = photoPaths;
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
        padding = dip2Px(8);
        this.size = size;
        this.index = index;

    }

    public PhotoAdapter(Context mContext, ArrayList<WorkOrderDetailBean.FileDto> photoPaths, int size, int index, Set<MimeType> mimeTypes,
                        PhotoOnClick photoOnClick) {
        this.photoPaths = photoPaths;
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
        padding = dip2Px(8);
        this.size = size;
        this.index = index;
        this.mimeTypes = mimeTypes;
        this.photoOnClick = photoOnClick;

    }


    PhotoOnClick photoOnClick = null;

    public PhotoAdapter(Context mContext, ArrayList<WorkOrderDetailBean.FileDto> photoPaths, int size, int drawable, PhotoOnClick photoOnClick) {
        this.photoPaths = photoPaths;
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
        padding = dip2Px(8);
        this.size = size;
        this.drawable = drawable;
        this.photoOnClick = photoOnClick;

    }

    public void add(ArrayList<WorkOrderDetailBean.FileDto> photoPaths) {
        if (photoPaths != null && photoPaths.size() > 0) {
            this.photoPaths.addAll(photoPaths);
            notifyDataSetChanged();
        }

    }

    public void refresh(ArrayList<WorkOrderDetailBean.FileDto> photoPaths) {
        this.photoPaths.clear();

        if (photoPaths != null && photoPaths.size() > 0) {
            this.photoPaths.addAll(photoPaths);
        }
        notifyDataSetChanged();
    }


    @Override
    public PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.__picker_item_photo, parent, false);
        return new PhotoViewHolder(itemView);
    }

    public int dip2Px(int dip) {
        // px/dip = density;
        float density = mContext.getResources().getDisplayMetrics().density;
        int px = (int) (dip * density + .5f);
        return px;
    }

    int padding;

    @Override
    public void onBindViewHolder(@NonNull PhotoViewHolder holder, @SuppressLint("RecyclerView") int position) {

        if (action == MultiPickResultView.ACTION_SELECT) {
            // RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.ivPhoto.getLayoutParams();

            holder.ivPhoto.setPadding(padding, padding, padding, padding);

            if (photoPaths.size() == size) {
                String str = photoPaths.get(position).getFilePath();
                Glide.with(mContext)
                        .load(str)
                        .centerCrop()
                        .thumbnail(0.1f)
                        // .bitmapTransform(new RoundedCornersTransformation(mContext,6,0))
                        .error(R.drawable.__picker_ic_broken_image_black_48dp)
                        .into(holder.ivPhoto);


                holder.deleteBtn.setVisibility(View.VISIBLE);
                holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        photoPaths.remove(position);
                        notifyDataSetChanged();
                    }
                });

                holder.ivPhoto.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PhotoPreview.builder()
                                .setPhotos(photoPaths)
                                .setAction(action)
                                .setCurrentItem(position)
                                .start((Activity) mContext);
                    }
                });
            } else {


                if (position == getItemCount() - 1) {//最后一个始终是+号，点击能够跳去添加图片
                    Glide.with(mContext)
                            .load("")
                            .centerCrop()
                            .thumbnail(0.1f)
                            .placeholder(drawable)
                            .error(drawable)
                            .into(holder.ivPhoto);
                    holder.ivPhoto.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String[] permission;

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                permission = new String[]{Manifest.permission.READ_MEDIA_IMAGES,
                                        Manifest.permission.READ_MEDIA_VIDEO,
                                        Manifest.permission.READ_MEDIA_AUDIO};
                            } else {
                                permission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.CAMERA};
                            }
                            new RxPermissions((FragmentActivity) mContext).request(permission).subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) {
                                    if (aBoolean) {

                                        if (photoPaths != null && photoPaths.size() == size) {
                                            Toast.makeText(mContext, "已选了" + size + "张图片", Toast.LENGTH_SHORT).show();
                                        } else {
                                            pickIndex = index;
                                            Matisse.from((Activity) mContext)
                                                    .choose(mimeTypes, false)
                                                    .capture(true) //默认只能拍照片
                                                    .setSelectedImages(photoPaths)
                                                    .captureStrategy(
                                                            new CaptureStrategy(true, "com.nsgf.skjc.fileprovider", "test"))
                                                    //.capture(true, CaptureMode.All)//通过CaptureMode控制拍照照片还是视频，或者都拍
                                                    .maxSelectable(5) //默认最大选中9张，设置为1就是单选
                                                    .theme(R.style.Matisse_Dracula)//暗色主题
                                                    //设置选中图片的监听器
                                                    .setOnSelectedListener(new OnSelectedListener() {
                                                        @Override
                                                        public void onSelected(
                                                                @NonNull List<Uri> uriList, @NonNull List<String> pathList) {
                                                            // DO SOMETHING IMMEDIATELY HERE
                                                            Log.e("onSelected", "onSelected: pathList=" + pathList);

                                                        }
                                                    })
                                                    .originalEnable(true)//是否显示原图，默认显示
                                                    //设置原图选中和取消选中的监听器
                                                    .setOnCheckedListener(new OnCheckedListener() {
                                                        @Override
                                                        public void onCheck(boolean isChecked) {
                                                            // DO SOMETHING IMMEDIATELY HERE
                                                            Log.e("isChecked", "onCheck: isChecked=" + isChecked);
                                                        }
                                                    })
                                                    .imageEngine(new GlideEngine()) // 默认是Glide4.x版本的加载器，如果你用的是Glide4.x，则无需设置
                                                    .setIndex(getPickIndex())
                                                    //.imageEngine(new Glide3Engine())//如果你用的是Glide3.x版本，Glide3Engine这个类在demo中
                                                    //.imageEngine(new PicassoEngine())//如果你用的是Picasso
                                                    .forResult(PhotoPicker.REQUEST_CODE); //请求码
                                        }

                                    } else {
                                        SysUtil.showPermissionDialog(mContext);
                                    }
                                }
                            });
                        }
                    });

                    holder.deleteBtn.setVisibility(View.GONE);

                } else {
                    String str = photoPaths.get(position).getFilePath();
                    Glide.with(mContext)
                            .load(str)
                            .centerCrop()
                            .thumbnail(0.1f)
                            // .bitmapTransform(new RoundedCornersTransformation(mContext,6,0))
                            .error(R.drawable.__picker_ic_broken_image_black_48dp)
                            .into(holder.ivPhoto);

                    holder.deleteBtn.setVisibility(View.VISIBLE);
                    holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            photoPaths.remove(position);
                            if (null != photoOnClick) {
                                photoOnClick.setPhotoListener(position);
                            }
                            notifyDataSetChanged();
                        }
                    });

                    holder.ivPhoto.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            PhotoPreview.builder()
                                    .setPhotos(photoPaths)
                                    .setAction(action)
                                    .setCurrentItem(position)
                                    .start((Activity) mContext);
                        }
                    });
                }
            }
        } else if (action == MultiPickResultView.ACTION_ONLY_SHOW) {
            //Uri uri = Uri.fromFile(new File(photoPaths.get(position)));
            //Uri uri = Uri.parse(photoPaths.get(position));
            Glide.with(mContext)
                    .load(photoPaths.get(position).getFilePath())
                    .centerCrop()
                    .thumbnail(0.1f)
                    // .bitmapTransform(new RoundedCornersTransformation(mContext,4,0))
                    .error(R.drawable.__picker_ic_broken_image_black_48dp)
                    .into(holder.ivPhoto);

            holder.ivPhoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    PhotoPreview.builder()
                            .setPhotos(photoPaths)
                            .setAction(action)
                            .setCurrentItem(position)
                            .start((Activity) mContext);
                }
            });
        }


    }

    @Override
    public int getItemCount() {
        if (action == MultiPickResultView.ACTION_SELECT) {
            if (photoPaths.size() == size)
                return size;
            else
                return photoPaths.size() + 1;
        } else
            return photoPaths.size();
    }


    public ArrayList<WorkOrderDetailBean.FileDto> getPhotoPaths() {
        if (photoPaths == null) {
            return photoPaths = new ArrayList<>();
        } else
            return photoPaths;
    }

    public int pickIndex;

    public void setPickIndex(int pickIndex) {
        this.pickIndex = pickIndex;
    }

    public int getPickIndex() {
        return pickIndex;
    }

    public static class PhotoViewHolder extends RecyclerView.ViewHolder {
        private ImageView ivPhoto;
        private View vSelected;
        public View cover;
        public View deleteBtn;

        public PhotoViewHolder(View itemView) {
            super(itemView);
            ivPhoto = (ImageView) itemView.findViewById(R.id.iv_photo);
            vSelected = itemView.findViewById(R.id.v_selected);
            vSelected.setVisibility(View.GONE);
            cover = itemView.findViewById(R.id.cover);
            cover.setVisibility(View.GONE);
            deleteBtn = itemView.findViewById(R.id.v_delete);
            deleteBtn.setVisibility(View.GONE);
        }
    }

    public interface PhotoOnClick {
        void setPhotoListener(int position);
    }

}
